package com.lauroc.dept.controller;

import com.lauroc.basic.utils.AjaxResult;
import com.lauroc.dept.domain.Department;
import com.lauroc.dept.query.DepartmentQuery;
import com.lauroc.dept.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


@RestController
@RequestMapping("/dept")
@Api(tags={"部门接口"})
public class DepartmentCotroller {

    @Autowired
    private IDepartmentService service;

    @ApiOperation(value="查询部门树", notes="部门的所有上下级")
    @GetMapping("/treeDepts")
    public AjaxResult treeDepts(){
        return AjaxResult.createSuccess(service.treeDepts());
    }

    @ApiOperation(value="查询上级部门信息", notes="部门信息")
    @GetMapping("/findParentDepts")
    public AjaxResult findParentDepts(){
        return AjaxResult.createSuccess(service.findParentDepts());
    }

    @ApiOperation(value="查询所有的部门信息", notes="分页查询部门信息")
    @PostMapping("/findPage")
    public AjaxResult findPage(@RequestBody DepartmentQuery department){
        return AjaxResult.createSuccess(service.findPage(department));
    }

    @ApiOperation(value="查询所有的部门信息", notes="详细描述")
    @GetMapping("/findAll")
    public AjaxResult getAll(){
        return AjaxResult.createSuccess(service.getAll());
    }

    @ApiOperation(value="新增或修改部门信息", notes="详细描述")
    @PostMapping("/save")
    public AjaxResult saveAndUpdate(@Valid @ApiParam(value = "新增或修改部门信息", required = true) @RequestBody Department department){
        try {
            service.saveAndUpdate(department);
            return AjaxResult.createSuccess();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return AjaxResult.createError(e.getMessage());
        }
        catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError("操作错误,请联系管理员");
        }
    }

    @ApiOperation(value="删除部门用户信息", notes="通过id删除部门信息")
    @DeleteMapping("/{id}")
    public AjaxResult delete(@ApiParam(value = "删除部门信息", required = true) @PathVariable("id") Long id){
        try {
            service.delete(id);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError("删除失败");
        }
    }


    @ApiOperation(value="批量部门用户信息", notes="通过ids删除部门信息")
    @PostMapping("/batchDelete")
    public AjaxResult batchDelete(@ApiParam(value = "删除部门信息", required = true)@RequestBody DepartmentQuery query){
        try {
            service.batchDelete(query.getIds());
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError("删除失败");
        }
    }
}
